package com.hzhk.happyrent.ui.activity.personal;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.person.BindModel;
import com.hzhk.happyrent.bean.person.CheckModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.utils.MyPerference;
import com.tamic.novate.Throwable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BindPhoneActivity extends Activity {

    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.reg_act_user_phone)
    ClearEditText regActUserPhone;
    @BindView(R.id.btn_sendvcode)
    Button btnSendvcode;
    @BindView(R.id.reg_vcode)
    ClearEditText regVcode;
    @BindView(R.id.btn_register)
    Button btnRegister;
    TimeCount time;
    @BindView(R.id.activity_titlebar_right)
    ImageView activityTitlebarRight;
    @BindView(R.id.reg_act_user_pwd)
    ClearEditText regActUserPwd;
    private Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        activityTitlebarCenter.setText(R.string.bind_verify);
        btnSendvcode.setEnabled(false);
        btnRegister.setEnabled(false);
        regActUserPhone.addTextChangedListener(new TextChange());
        regActUserPwd.addTextChangedListener(new TextChange());
        regVcode.addTextChangedListener(new TextChange());
        time = new TimeCount(59300, 100);
    }

    @OnClick({R.id.btn_sendvcode, R.id.btn_register,R.id.activity_titlebar_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sendvcode:
                getVCode();
                break;
            case R.id.btn_register:
                judgeVBind();
                break;
            case R.id.activity_titlebar_left:
                finish();
                break;
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            btnSendvcode.setText(R.string.get_again);
            btnSendvcode.setEnabled(true);
            btnSendvcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
            btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnSendvcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
            btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
            btnSendvcode.setEnabled(false);
            btnSendvcode.setText((millisUntilFinished + 800) / 1000 + "s");
        }
    }

    //发送验证码
    private void getVCode() {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", regActUserPhone.getText().toString());
        HttpManager.getInstance().perform_post(API.SMS_SEND, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel baseModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == baseModel.getErrCode()) {
                    Toast.makeText(BindPhoneActivity.this, R.string.apply_success, Toast.LENGTH_SHORT).show();
                    time.start();
                } else {
                    Toast.makeText(BindPhoneActivity.this, baseModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }

    //绑定手机号
    private void judgeVBind() {
        if (TextUtils.isEmpty(regVcode.getText().toString())) {
            Toast.makeText(BindPhoneActivity.this, R.string.tv_vcode_is_null, Toast.LENGTH_SHORT).show();
            return;
        } else if (regVcode.getText().toString().length() != 6) {
            Toast.makeText(BindPhoneActivity.this, R.string.tv_isnot_vcode, Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = getIntent();
        log.debug("open_id = " +intent.getStringExtra("open_id"));
        // TODO: 2017/12/31 这里需要传入微信id
        Map<String, Object> params = new HashMap<>();
        params.put("open_id", intent.getStringExtra("open_id"));
        params.put("phone", regActUserPhone.getText().toString());
        params.put("code", regVcode.getText().toString());
        params.put("password", regActUserPwd.getText().toString());
        HttpManager.getInstance().perform_post(API.BIND_PHONE, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                log.debug("response" + response);
                CodeModel codeModel = new  Gson().fromJson(response, CodeModel.class);
                if (codeModel.getErrCode() == 0) {
                    BindModel bindModel=new Gson().fromJson(response, BindModel.class);
                    log.debug("bindModel.getErrCode() = " + bindModel.getErrCode());
                    Toast.makeText(BindPhoneActivity.this, bindModel.getMessage(), Toast.LENGTH_SHORT).show();
                    MyPerference.getInstance().setUserInfoSave(bindModel.getData().getId(),
                            bindModel.getData().getPhone(),
                            bindModel.getData().getPassword(),
                            bindModel.getData().getIs_auth());
                    finish();
                }
               else {
                    Toast.makeText(BindPhoneActivity.this, codeModel.getMessage(), Toast.LENGTH_SHORT).show();
                    regVcode.setText("");
                    regActUserPhone.setText("");
                    regActUserPwd.setText("");
                    return;
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }
    class TextChange implements TextWatcher {

        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                                  int count) {
            boolean Sign1 = regActUserPhone.getText().length() > 10;
            boolean Sign2 = regActUserPwd.getText().length() > 5;
            boolean Sign3 = regVcode.getText().length() > 5;
            if (Sign1 & Sign2) {
                btnSendvcode
                        .setBackgroundResource(R.drawable.btn_red_selector);
                btnSendvcode.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnSendvcode
                        .setBackgroundResource(R.drawable.bg_btn_gray_solid);
                btnSendvcode.setEnabled(false);
            }
            if (Sign1 & Sign2 &Sign3) {
                btnRegister
                        .setBackgroundResource(R.drawable.btn_red_selector);
                btnRegister.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnRegister
                        .setBackgroundResource(R.drawable.bg_btn_gray_solid);
                btnRegister.setEnabled(false);
            }

        }
    }
}
